package com.kurumi.medical.exception;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
@Configuration
public class MyExceptionResolver extends SimpleMappingExceptionResolver  {
	private Logger log = LoggerFactory.getLogger(MyExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		
		System.out.println(HttpServletResponse.SC_BAD_REQUEST+"----------------------");
		// TODO Auto-generated method stub  
        System.out.println("==============异常开始=============");  
        //如果是shiro无权操作，因为shiro 在操作auno等一部分不进行转发至无权限url  
     // 判断是否 Ajax 请求 
        if ((request.getHeader("accept").indexOf("application/json") > -1 ||
          (request.getHeader("X-Requested-With") != null && 
          request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))){

           try {
        	   if(ex instanceof UnauthorizedException) {
        		   response.setStatus(403);
        	   } else {
        		   response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        	   }
        	   
               response.setContentType("text/html;charset=UTF-8");
               response.setCharacterEncoding("UTF-8");
               PrintWriter writer = response.getWriter();
               writer.write(ex.getMessage());
               writer.flush();
               writer.close();
           } catch (Exception e) {
        	   log.error(e.getMessage());
              // LogHelper.info(e);
           }
           return null;
       }

        
        if(ex instanceof UnauthorizedException){  
        	
//            ModelAndView mv = new ModelAndView();
//            mv.setViewName("unauthorized");
//        	response.setContentType("text/html");
//        	try {
//        		//response.sendError(403, "no authority");
//				//response.getWriter().print("没有权限！");
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
            return new ModelAndView("error/unAuthority");  
        }  
//        

        
        ex.printStackTrace();  
        System.out.println("==============异常结束=============");  
        ModelAndView mv = new ModelAndView("error");  
        mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>"));  
        return mv;  
	}

}
